package com.nd.mobile.study.view;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.widget.TextView;

import com.nd.mobile.study.R;
import com.nd.mobile.study.common.BaseActivity;
import com.nd.mobile.study.common.constants.BundleConstants;
import com.nd.mobile.study.common.util.ExceptionHandler;
import com.nd.mobile.study.domain.News;
import com.nd.mobile.study.domain.NewsDetail;
import com.nd.mobile.study.view.helper.ToastHelper;
import com.nd.mobile.study.view.widget.Loading;

public class NewsDetailActivity extends BaseActivity {

	private TextView mTVTitle;
	private TextView mTVDate;
	private TextView mTVContent;
	private News mNews;
	
	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.news_detail);
	}

	@Override
	protected void initViews() {
		super.initHeader();
		mHeaderTitleTv.setText(R.string.news_title);
		mTVTitle = (TextView)findViewById(R.id.news_detail_subtitle);
		mTVDate = (TextView)findViewById(R.id.news_detail_date);
		mTVContent = (TextView)findViewById(R.id.news_detail_content);
	}

	@Override
	protected void setFieldValues() {
		mNews = (News)getIntent().getSerializableExtra(BundleConstants.NEWS);
	}

	@Override
	protected void onAfterCreate(Bundle savedInstanceStat) {
		showDetail();
	}

	private void showDetail() {
		mLoading.p();
		new GetDetailTask().execute();
	}
	
	private class GetDetailTask extends AsyncTask<Void, Void, String>{
		
		private NewsDetail	mDetail;

		@Override
		protected String doInBackground(Void... params) {
			String errorMsg = null;
			try {
				mDetail = mNews.getDetail().getBody();
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = ExceptionHandler.parseExceptionInfo(e);
			}
			return errorMsg;
		}

		@Override
		protected void onPostExecute(String errorMsg) {
			super.onPostExecute(errorMsg);
			if(null != errorMsg){
				ToastHelper.displayToast(NewsDetailActivity.this, errorMsg);
			}else{
				handleDetail(mDetail);
			}
		}

		private void handleDetail(NewsDetail detail) {
			mTVTitle.setText(detail.getTitle());
			mTVDate.setText(detail.getDate());
			mTVContent.setText(Html.fromHtml(detail.getContentNote()));
			mLoading.v();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean result = false;
		if(KeyEvent.KEYCODE_BACK == keyCode){
			result = true;
			finish();
		}
		return result;
	}
}
